package br.ucb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.ucb.connection.MyConnection;
import br.ucb.model.Cliente;

public class ClienteDao {
	public void add(Cliente cliente) {
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "INSERT INTO CLIENTE VALUES(?,?,?,?,?,?,?,0);";
			st = con.prepareStatement(sql);
			st.setString(1, cliente.getNome());
			st.setString(2, cliente.getEmail());
			st.setString(3, cliente.getEndereco());
			st.setInt(4, 0);
			st.setInt(5, cliente.getTelefone());
			st.setString(6, cliente.getCpf());
			st.setDate(7, null);
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public List<Cliente> findAll() {
		Connection con;
		Statement st;
		ResultSet rs;
		String sql;
		List<Cliente> clientes = new ArrayList<Cliente>();

		try {
			con = MyConnection.getConnection();
			st = con.createStatement();
			sql = "SELECT * FROM CLIENTE;";
			rs = st.executeQuery(sql);
			while (rs.next()) {
				clientes.add(new Cliente(rs.getString("nome"), 
						rs.getString("cpf"), rs.getInt("id"),
						null,rs.getString("email"),
						rs.getString("endereco"),rs.getInt("telefone")));
			}
			MyConnection.closeConnection(con, st, rs);
		} catch (SQLException e){
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return clientes;
	}

	public void update(Cliente cliente) {
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "UPDATE CLIENTE SET EMAIL=?,TElEFONE=?,ENDERECO=? where ID=?;";
			st = con.prepareStatement(sql);
			st.setString(1, cliente.getEmail());
			st.setInt(2, cliente.getTelefone());
			st.setString(3, cliente.getEndereco());
			st.setInt(4, cliente.getId());
		//email, endereco, telefone e foto	
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void delete(Cliente cliente) {
		Connection con;
		PreparedStatement st;
		String sql = "";
		try {
			con = MyConnection.getConnection();
			sql = "DELETE FROM CLIENTE WHERE ID=?;";
			st = con.prepareStatement(sql);
			st.setInt(1, cliente.getId());
			st.execute();
			MyConnection.closeConnection(con, st);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
